package com.uyaer.wheel.display.scene
{
	import com.uyaer.wheel.common.Common;
	import com.uyaer.wheel.common.Config;
	import com.uyaer.wheel.common.Platform;
	import com.uyaer.wheel.common.UserData;
	import com.uyaer.wheel.display.scene.el.Cloud;
	import com.uyaer.wheel.display.scene.el.ElPool;
	import com.uyaer.wheel.display.scene.el.ElementBase;
	import com.uyaer.wheel.display.scene.role.Ball;
	import com.uyaer.wheel.events.EventManager;
	import com.uyaer.wheel.events.EventType;
	import com.uyaer.wheel.events.MyEvent;
	import com.uyaer.wheel.menu.MenuItem;
	import com.uyaer.wheel.menu.MenuType;
	import com.uyaer.wheel.plus.AD;
	import com.uyaer.wheel.plus.Audio;
	import com.uyaer.wheel.res.ResManager;
	import com.uyaer.wheel.story.Story;
	import com.uyaer.wheel.tick.TimerManager;
	import com.uyaer.wheel.utils.Utils;
	
	import flash.desktop.NativeApplication;
	import flash.events.KeyboardEvent;
	import flash.geom.Point;
	import flash.net.URLRequest;
	import flash.net.navigateToURL;
	import flash.ui.Keyboard;
	
	import starling.animation.Transitions;
	import starling.core.Starling;
	import starling.display.Button;
	import starling.display.Image;
	import starling.display.MovieClip;
	import starling.display.Quad;
	import starling.display.Sprite;
	import starling.events.Event;
	import starling.events.Touch;
	import starling.events.TouchEvent;
	import starling.events.TouchPhase;
	import starling.text.TextField;
	import starling.textures.Texture;
	import starling.utils.HAlign;
	import starling.utils.VAlign;
	import starling.utils.deg2rad;
	
	/**
	 *最开始选择游戏菜单的界面 
	 * @author hc
	 * 
	 */	
	public class Home extends Sprite implements IScene
	{
		private var btnItems:Array = [ 
							{"name":MenuItem.START_GAME,"textureName":"menu_startgame"},
							{"name":MenuItem.HELP,"textureName":"menu_help"},
							{"name":MenuItem.ABOUTUS,"textureName":"menu_aboutus"},
							{"name":MenuItem.LOVEME,"textureName":"menu_loveme"}
							];
		private var talkArr:Array;
		private var menuContainer:Sprite;
		private var btnList:Vector.<Button> = new Vector.<Button>();
		private var elList:Vector.<ElementBase> = new Vector.<ElementBase>();
		private var elContainer:Sprite;
		
		private var ballRole:Ball; 
		private var runBall:Image;
		private var startPos:Point = new Point();
		private var movePoint:Point = new Point();
		private var startPY:Number = 0;  //拖动前的位置
		private var loveMeBtnIndex:int = 0;
		private var butterflyIndex:int = 0;
		private var butterfly:Image;
		private var maxScoreImg:Image;
		private var maxScoreTF:TextField;

		private var music:Image;

		private var talk:Sprite;

		private var talkTF:TextField;
		
		public function Home()
		{
			if(stage){
				onAdded();
			}else{
				this.addEventListener(Event.ADDED_TO_STAGE,onAdded);
			}
		}
		
		private function onAdded(e:Event = null):void{
			this.removeEventListener(Event.ADDED_TO_STAGE,onAdded);
			
			if(Config.platform == Platform.MOBILE){
				talkArr = ["爱我就帮我点击吧","点击一下应该没有什么吧？","你的点击是对我们最好的支持","点击没有啊，人家都要睡着了"];
			}else{
				talkArr = ["喜欢我就摸摸我吧","听说这个游戏还有手机版本的哦","好无聊，没有人陪我玩","你喜欢我吐泡泡吗？可爱极了"];
			}
			
			this.layout();
		}
		
		private function onMenuTouchHandler(e:TouchEvent):void{
			e.stopImmediatePropagation();
			e.stopPropagation();
		}
		
		private function onTouchHandler(e:TouchEvent):void{
			var touch:Touch = e.getTouch(this);
			if(touch){
				if(e.target is MovieClip && touch.phase == TouchPhase.ENDED && Config.platform == Platform.WEB){
					ballRole.isHappy = true;
				}else if(e.target == music && touch.phase == TouchPhase.ENDED){
					Config.MUSIC = !Config.MUSIC;
					music.texture = ResManager.me.getTexture(Config.MUSIC?"menu_music_open":"menu_music_close");
					if(Config.MUSIC){
						Audio.me.playHome();
					}else{
						Audio.me.stopHome();
					}
					this.y = 0;
				}else{
					switch(touch.phase){
						case TouchPhase.BEGAN:
							startPos.setTo(touch.globalX,touch.globalY);
							startPY = this.y;
							break;
						case TouchPhase.ENDED:
							if(startPos.y - touch.globalY > (100 / Common.S)){
								showBottom((Common.H+this.y)/Common.H);
							}else if(startPos.y - touch.globalY < (-100 / Common.S)){
								showTop(Math.abs(this.y)/Common.H);
							}else{
								Starling.juggler.tween(this,0.1,{y:startPY,"transition":Transitions.EASE_OUT});
							}
							break;
						case TouchPhase.MOVED:
							movePoint = touch.getMovement(this,movePoint);
							this.y += movePoint.y;
							if(this.y >0){
								this.y = 0;
							}else if(this.y<-Common.H){
								this.y = -Common.H;
							}
							break;
					}
				}
			}
		}
		
		private function onTriggered(e:Event):void{
			var btn:Button = Button(e.target);
			switch(btn.name)
			{
				case MenuItem.START_GAME:
					this.stop();
					stage.dispatchEventWith(EventType.MENU_SELECT,false,MenuType.START_GAME);
					break;	
				case MenuItem.ABOUTUS:
					navigateToURL(new URLRequest("http://www.uyaer.com"),"-blank");
					break;	
				case MenuItem.HELP:
					Story.instance.showGuide();
					break;	
				case MenuItem.LOVEME:
					showBottom();
					break;	
			}
		}
		
		private function showBottom(per:Number = 1.0):void{
			Starling.juggler.tween(this,0.75 * per,{y:-Common.H,"transition":Transitions.EASE_OUT,
						"onComplete":function():void{
							AD.me.showHomeAD();
						}});
		}
		private function showTop(per:Number = 1.0):void{
			Starling.juggler.tween(this,0.75 * per,{y:0,"transition":Transitions.EASE_OUT,
						"onComplete":function():void{
							AD.me.hideAD();
						}});
		}
		
		private function addPopHandler(e:Event):void{
			var el:ElementBase = e.data as ElementBase;
			elContainer.addChild(el);
			elList.push(el);
		}
		
		private function layout():void{
			var q_top:Quad = new Quad(Common.W,Common.H);
			q_top.setVertexColor(0,0x0677ce);
			q_top.setVertexColor(1,0x0677ce);
			q_top.setVertexColor(2,0x48a2f5);
			q_top.setVertexColor(3,0x48a2f5);
			addChild(q_top);
			var q_bottom:Quad = new Quad(Common.W,Common.H);
			q_bottom.setVertexColor(0,0x48a2f5);
			q_bottom.setVertexColor(1,0x48a2f5);
			q_bottom.setVertexColor(2,0xacd8f4);
			q_bottom.setVertexColor(3,0xacd8f4);
			q_bottom.y = Common.H;
			addChild(q_bottom);
			
			var bottomContainer:Sprite = new Sprite();
			addChild(bottomContainer);
			var titleContainer:Sprite = new Sprite();
			titleContainer.touchable = false;
			addChild(titleContainer);
			elContainer = new Sprite();
			elContainer.touchable = false;
			addChild(elContainer);
			menuContainer = new Sprite();
			menuContainer.addEventListener(TouchEvent.TOUCH,onMenuTouchHandler);
			addChild(menuContainer);
			
			//初始化logo
			var title:Image = new Image(ResManager.me.getTexture("home_title"));
			titleContainer.addChild(title);
			runBall = new Image(ResManager.me.getTexture("home_runball"));
			runBall.pivotX = runBall.pivotY = runBall.width >> 1;
			runBall.x = 155;
			runBall.y = 45;
			titleContainer.addChild(runBall);
			butterfly = new Image(ResManager.me.getTexture("home_butterfly"));
			titleContainer.addChild(butterfly);
			var line:Image = new Image(ResManager.me.getTexture("home_line"));
			line.pivotY = line.height;
			line.x = runBall.x;
			line.y = runBall.y;
			titleContainer.addChild(line);
			butterfly.x = line.x+line.width-3.5;
			butterfly.y = 8.5;
			butterfly.pivotX = butterfly.width>>1;
			butterfly.pivotY = butterfly.height>>1;
			butterfly.rotation = deg2rad(-40);
			
			titleContainer.pivotX = titleContainer.width>>1;
			titleContainer.x = Common.W >> 1;
			titleContainer.y = Common.H * 0.12;
			
			titleContainer.scaleX = titleContainer.scaleY = Common.S;
			
			//初始化菜单
			var btn:Button;
			for (var i:int = 0; i < btnItems.length; i++){
				btn = new Button(ResManager.me.getTexture(btnItems[i].textureName));
				btn.pivotX = btn.width >> 1;
				btn.scaleX = btn.scaleY = Common.S;
				btn.x = -1000;
				btn.y = (0.35+i * 0.13) * Common.H;
				btn.name = btnItems[i].name;
				menuContainer.addChild(btn);
				btnList.push(btn);
			}
			
			//初始化云朵
			var cloud:Cloud;
			var cn:Number = Common.H / 3;
			for(i = 0 ; i < 5 ; i ++){
				cloud = ElPool.getCloud();
				cloud.x = Utils.rangInt(0,Common.W);
				cloud.y = Utils.rangInt(i * cn,(i+1) * cn);
				var sr:Number = Utils.rangInt(80,100) / 100.0 * Common.S;
				cloud.scaleX = cloud.scaleY = sr;
				elContainer.addChild(cloud);
				elList.push(cloud);
			}
			
			var hillTexture:Texture = ResManager.me.getTexture("home_hill");
			var hill:Image = new Image(hillTexture);
			if (hillTexture.width<Common.W){
				hillTexture.repeat = true;
				hill.width = Common.W;
				hill.setTexCoords(1,new Point(Common.W/hillTexture.width,0));
				hill.setTexCoords(3,new Point(Common.W/hillTexture.width,1));
			}else{
			}
			hill.pivotY = hill.height;
			hill.y = Common.H << 1;
			hill.touchable = false;
			bottomContainer.addChild(hill);
			
			ballRole = new Ball();
			ballRole.scaleX = ballRole.scaleY = Math.min(1,Common.W/hillTexture.width);
			ballRole.x = 0.45 * Common.W - ballRole.width*0.5;
			ballRole.y = hill.y - 20 * Math.min(1,Common.W/hillTexture.width)-ballRole.height;
			bottomContainer.addChild(ballRole);
			
			if(Config.platform == Platform.MOBILE){
				var supportMe:TextField = new TextField(Common.W,140*Common.S,"你的点击\n就是对我们最大的支持");
				supportMe.fontSize = 52*Common.S;
				supportMe.color = 0xffff22;
				supportMe.y = Common.H*1.2-supportMe.height;
				bottomContainer.addChild(supportMe);
			}
			
			talk = new Sprite();
			bottomContainer.addChild(talk);
			var talkbg:Image = new Image(ResManager.me.getTexture("home_talk"));
			talk.addChild(talkbg);
			talkTF = new TextField(160,120,talkArr[0]);
			talkTF.hAlign = HAlign.LEFT;
			talkTF.fontSize = 26;
			talkTF.x = talkTF.y = 20*ballRole.scaleX;
			talkTF.color = 0x6dc3e3;
			talk.addChild(talkTF);
			talk.x = ballRole.x+ballRole.width*0.62;
			talk.y = ballRole.y-17;
			talk.scaleX = talk.scaleY = ballRole.scaleX;
			
			maxScoreImg = new Image(ResManager.me.getTexture("menu_max_score"));
			maxScoreImg.scaleX = maxScoreImg.scaleY = Common.S;
			maxScoreImg.x = 8;
			maxScoreImg.y = (60*Common.S-maxScoreImg.height)*0.5;
			
			maxScoreTF = new TextField(Common.W*0.5,60*Common.S,
						""+UserData.me.maxStarCount,Common.FONT,52*Common.S,0xffff22);
			maxScoreTF.hAlign = HAlign.LEFT;
			maxScoreTF.vAlign = VAlign.CENTER;
			maxScoreTF.x = 16 + maxScoreImg.width;
			
			music = new Image(ResManager.me.getTexture(Config.MUSIC?"menu_music_open":"menu_music_close"));
			music.scaleX = music.scaleY = Math.max(Common.S,0.75);
			music.x = Common.W - music.width-12;
			music.y = 12;
			addChild(music);
			
		}
		
		public function reLayout():void{
			this.removeChildren();
			layout();
		}
		
		private function updateElement():void{
			var el:ElementBase;
			for (var i:int = elList.length -1; i >=0; i--){
				el = elList[i]; 
				el.move();
				if(el.y <= 0){
					el.recycle();
					elList.splice(i,1);
				}
			}
			runBall.rotation+=0.035;
			
			if(loveMeBtnIndex<5){
				btnList[btnList.length-1].y +=3;
			}else if(loveMeBtnIndex<10){
				btnList[btnList.length-1].y -=3;
			}
			loveMeBtnIndex++;
			if(loveMeBtnIndex == 10){
				loveMeBtnIndex = 0;
			}
			if(butterflyIndex<10){
				butterfly.scaleY -=0.03;
			}else if(butterflyIndex<20){
				butterfly.scaleY +=0.03;
			}
			butterflyIndex++;
			if(butterflyIndex == 20){
				butterflyIndex = 0;
			}
		}
		
		private function onKeyHandler(e:KeyboardEvent):void{
			if(e.type == KeyboardEvent.KEY_DOWN){
				if(e.keyCode == Keyboard.BACK){
					e.preventDefault();
					e.stopPropagation();
					AD.me.hideAD();
					this.exit();
				}
			}
		}
		
		private function exit():void{
			AD.me.hideAD();
			Story.instance.showAlert("确定要退出？",function():void{
				NativeApplication.nativeApplication.exit();
			});
		}
		
		private function maxScoreChangeHandler():void{
			if(UserData.me.maxStarCount>0){
				addChild(maxScoreImg);
				addChild(maxScoreTF);
				maxScoreTF.text = UserData.me.maxStarCount+"";
			}else{
				maxScoreImg.removeFromParent();
				maxScoreTF.removeFromParent();
				maxScoreTF.text = "";
			}
		}
		
		private function updateTalk():void{
			if(talk.visible){
				Starling.juggler.tween(talk,1,{"alpha":0,"onComplete":function():void{
					talk.visible = false;
				}});
			}else{
				talkTF.text = talkArr[Utils.rangInt(0,3)];
				talk.visible = true;
				Starling.juggler.tween(talk,1,{"alpha":1});
			}
		}
		
		private function onAdClicked(e:MyEvent):void{
			ballRole.isHappy = true;
		}
		
		/**
		 *开始动画 
		 */		
		public function start():void{
			stage.addEventListener(EventType.HOME_ADD_POP,addPopHandler);
			this.addEventListener(EventType.MAX_SCORE_CHANGE,maxScoreChangeHandler);
			this.addEventListener(Event.TRIGGERED,onTriggered);
			this.addEventListener(TouchEvent.TOUCH,onTouchHandler);
			Common.stage.addEventListener(KeyboardEvent.KEY_DOWN,onKeyHandler);
			Common.stage.addEventListener("deactivate",onDeactivate);
			Common.stage.addEventListener("activate",onActivate);
			EventManager.addEvent(EventType.AD_CLICKED,onAdClicked);
			
			TimerManager.addLoop(updateElement,33);
			TimerManager.addLoop(updateTalk,4500);
			ballRole.popEl();
			
			for(var i:int = 0 ; i < btnList.length ; i ++){
				if(i%2==0){
					btnList[i].x = -btnList[i].width;
				}else{
					btnList[i].x = Common.W + btnList[i].width;
				}
				Starling.juggler.tween(btnList[i],1.8,{"x":Common.W>>1,
							"transition":Transitions.EASE_IN_OUT_ELASTIC})
			}
			
			maxScoreChangeHandler();
			
			Audio.me.playHome();
		}
		
		private function onDeactivate(e:*):void{
			Audio.me.stopHome();			
		}
		private function onActivate(e:*):void{
			Audio.me.playHome();			
		}
		
		/**
		 *停止动画
		 * 
		 */		
		public function stop():void{
			stage.removeEventListener(EventType.HOME_ADD_POP,addPopHandler);
			this.removeEventListener(Event.TRIGGERED,onTriggered);
			this.removeEventListener(TouchEvent.TOUCH,onTouchHandler);
			Common.stage.removeEventListener(KeyboardEvent.KEY_DOWN,onKeyHandler);
			Common.stage.removeEventListener("deactivate",onDeactivate);
			Common.stage.removeEventListener("activate",onActivate);
			EventManager.removeEvent(EventType.AD_CLICKED,onAdClicked);
			
			ballRole.isHappy = false;
			TimerManager.removeLoop(updateElement);
			TimerManager.removeLoop(updateTalk);
			ballRole.stopEl();
			
			Audio.me.stopHome();
		}
	}
}